<template>
  <div class="edit-user-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <a-button type="text" @click="handleBack" class="back-btn">
          <ArrowLeftOutlined />
          返回
        </a-button>
        <h1 class="page-title">编辑个人资料</h1>
        <div></div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="page-content">
      <div class="edit-form-container">
        <a-form
          :model="formState"
          name="editUserForm"
          :rules="rules"
          @finish="onFinish"
          layout="vertical"
          :colon="false"
        >
          <!-- 头像上传区域 -->
          <div class="avatar-section">
            <div class="avatar-wrapper">
              <a-avatar :size="100" :src="formState.userAvatar || defaultAvatar" class="user-avatar">
                <template #icon><UserOutlined /></template>
              </a-avatar>
              <div class="avatar-upload" @click="triggerUpload">
                <CameraOutlined />
              </div>
            </div>
            <div class="avatar-info">
              <h3>头像</h3>
              <p>点击右下角图标更换头像</p>
              <p class="upload-tip">支持 JPG、PNG 格式，不超过 2MB</p>
            </div>
            <input
              ref="fileInput"
              type="file"
              accept="image/jpeg,image/png"
              style="display: none"
              @change="handleFileChange"
            />
          </div>

          <!-- 表单字段 -->
          <div class="form-fields">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item label="用户名" name="userName">
                  <a-input
                    v-model:value="formState.userName"
                    placeholder="请输入用户名"
                    size="large"
                    :maxlength="20"
                    show-count
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="邮箱地址" name="email">
                  <a-input
                    v-model:value="formState.email"
                    placeholder="请输入邮箱地址"
                    size="large"
                    type="email"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item label="个人简介" name="userProfile">
              <a-textarea
                v-model:value="formState.userProfile"
                placeholder="介绍一下自己吧..."
                :rows="4"
                :maxlength="200"
                show-count
              />
            </a-form-item>
          </div>

          <!-- 操作按钮 -->
          <div class="form-actions">
            <a-space size="large">
              <a-button size="large" @click="handleCancel">
                取消
              </a-button>
              <a-button
                type="primary"
                html-type="submit"
                size="large"
                :loading="loading"
              >
                保存修改
              </a-button>
            </a-space>
          </div>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { 
  UserOutlined, 
  CameraOutlined, 
  ArrowLeftOutlined 
} from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { updateUserInfo, getLoginUser } from '@/api/userController'
import { uploadImage } from '@/api/tongyongjiekou'
import type { Rule } from 'ant-design-vue/es/form'

const router = useRouter()
const loginUserStore = useLoginUserStore()
const loading = ref(false)
const fileInput = ref<HTMLInputElement>()

// 默认头像
const defaultAvatar = 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png'

// 表单数据
const formState = reactive<API.UserUpdateDTO>({
  id: undefined,
  userName: '',
  userAvatar: '',
  userProfile: '',
  email: '',
})

// 表单验证规则
const rules: Record<string, Rule[]> = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度应在2-20个字符之间', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' },
  ],
  userProfile: [
    { max: 200, message: '个人简介不能超过200个字符', trigger: 'blur' },
  ],
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getLoginUser()
    if (res.data.code === 200 && res.data.data) {
      const userData = res.data.data
      formState.id = userData.id
      formState.userName = userData.userName || ''
      formState.userAvatar = userData.userAvatar || ''
      formState.userProfile = userData.userProfile || ''
      formState.email = userData.email || ''
    }
  } catch (error) {
    console.error('获取用户信息失败：', error)
    message.error('获取用户信息失败')
  }
}

// 触发文件选择
const triggerUpload = () => {
  fileInput.value?.click()
}

// 处理文件选择
const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (!file) return
  
  // 验证文件类型
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传 JPG/PNG 格式的图片!')
    return
  }
  
  // 验证文件大小
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过 2MB!')
    return
  }
  
  // 上传图片
  await uploadAvatar(file)
  
  // 清空input值，允许重复选择同一文件
  target.value = ''
}

// 上传头像 - 使用API封装但正确处理二进制数据
const uploadAvatar = async (file: File) => {
  const loadingMessage = message.loading('正在上传头像...', 0)
  
  try {
    // 创建FormData对象，用于二进制文件上传
    const formData = new FormData()
    formData.append('image', file)
    
    // 使用API封装，但覆盖headers来正确处理FormData
    const res = await uploadImage(formData as any, {
      headers: {
        // 不设置Content-Type，让浏览器自动设置multipart/form-data
      },
      // 确保request库正确处理FormData
      data: formData,
    })
    
    if (res.data.code === 200 && res.data.data) {
      formState.userAvatar = res.data.data
      message.success('头像上传成功')
    } else {
      message.error(res.data.message || '头像上传失败')
    }
  } catch (error) {
    console.error('头像上传失败：', error)
    message.error('头像上传失败，请重试')
  } finally {
    loadingMessage()
  }
}

// 提交表单
const onFinish = async (values: API.UserUpdateDTO) => {
  try {
    loading.value = true
    
    // 合并表单数据和头像数据
    const submitData: API.UserUpdateDTO = {
      ...values,
      id: formState.id,
      userAvatar: formState.userAvatar, // 确保包含头像数据
    }
    
    console.log('提交的完整数据：', submitData) // 调试日志
    
    const res = await updateUserInfo(submitData)
    
    if (res.data.code === 200 && res.data.data) {
      message.success('个人资料更新成功')
      
      // 更新本地用户信息
      loginUserStore.setLoginUser(res.data.data)
      
      // 跳转回首页
      setTimeout(() => {
        router.push('/')
      }, 1500)
    } else {
      message.error(res.data.message || '更新失败，请重试')
    }
  } catch (error) {
    console.error('更新用户信息失败：', error)
    message.error('更新失败，请检查网络后重试')
  } finally {
    loading.value = false
  }
}


// 取消编辑
const handleCancel = () => {
  router.back()
}

// 返回上一页
const handleBack = () => {
  router.back()
}

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.edit-user-page {
  min-height: 100vh;
  background: #f8fafc;
}

.page-header {
  background: #ffffff;
  border-bottom: 1px solid #e5e7eb;
  padding: 0 32px;
}

.header-content {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.back-btn {
  color: #6b7280;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border-radius: 6px;
  transition: all 0.2s;
}

.back-btn:hover {
  color: #3b82f6;
  background: #eff6ff;
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #111827;
  margin: 0;
}

.page-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 32px;
}

.edit-form-container {
  background: #ffffff;
  border-radius: 12px;
  padding: 32px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e5e7eb;
}

.avatar-section {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 24px;
  background: #f9fafb;
  border-radius: 8px;
  margin-bottom: 32px;
  border: 1px solid #e5e7eb;
}

.avatar-wrapper {
  position: relative;
  flex-shrink: 0;
}

.user-avatar {
  border: 3px solid #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.avatar-upload {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 32px;
  height: 32px;
  background: #3b82f6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  border: 3px solid #ffffff;
  transition: all 0.2s;
  font-size: 14px;
}

.avatar-upload:hover {
  background: #2563eb;
  transform: scale(1.1);
}

.avatar-info h3 {
  font-size: 16px;
  font-weight: 600;
  color: #111827;
  margin: 0 0 8px 0;
}

.avatar-info p {
  font-size: 14px;
  color: #6b7280;
  margin: 0 0 4px 0;
}

.upload-tip {
  font-size: 12px !important;
  color: #9ca3af !important;
}

.form-fields {
  margin-bottom: 32px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 600;
  color: #374151;
  font-size: 14px;
}

:deep(.ant-input) {
  border-radius: 8px;
  border: 1px solid #d1d5db;
  transition: all 0.2s;
}

:deep(.ant-input:hover) {
  border-color: #9ca3af;
}

:deep(.ant-input:focus) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

:deep(.ant-input-lg) {
  padding: 10px 12px;
  height: 40px;
}

:deep(.ant-input-affix-wrapper) {
  border-radius: 8px;
  border: 1px solid #d1d5db;
}

:deep(.ant-input-affix-wrapper:hover) {
  border-color: #9ca3af;
}

:deep(.ant-input-affix-wrapper:focus-within) {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

:deep(.ant-input-affix-wrapper-lg) {
  padding: 10px 12px;
}

:deep(.ant-input-affix-wrapper-lg .ant-input) {
  padding: 0;
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

.form-actions {
  text-align: right;
  padding-top: 24px;
  border-top: 1px solid #e5e7eb;
}

.form-actions .ant-btn {
  height: 40px;
  border-radius: 8px;
  font-weight: 500;
  min-width: 80px;
}

.form-actions .ant-btn-primary {
  background: #3b82f6;
  border-color: #3b82f6;
}

.form-actions .ant-btn-primary:hover {
  background: #2563eb;
  border-color: #2563eb;
}

/* 表单验证错误样式 */
:deep(.ant-form-item-has-error .ant-input) {
  border-color: #ef4444;
}

:deep(.ant-form-item-has-error .ant-input:focus) {
  border-color: #ef4444;
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-content {
    padding: 16px;
  }
  
  .edit-form-container {
    padding: 24px 16px;
  }
  
  .avatar-section {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .header-content {
    padding: 0 16px;
  }
  
  .form-actions {
    text-align: center;
  }
  
  .form-actions .ant-space {
    width: 100%;
  }
  
  .form-actions .ant-btn {
    flex: 1;
    max-width: 120px;
  }
}

@media (max-width: 576px) {
  .form-fields .ant-col {
    width: 100% !important;
    max-width: 100% !important;
  }
}
</style>